/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package cn.eclass.servlet.admin;

import cn.eclass.bean.api.IAdCategoryBean;
import cn.eclass.entity.AdCategoryEntity;
import cn.eclass.servlet.ActionFace;
import cn.eclass.utils.BeanFactory;
import cn.eclass.utils.Helper;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;

/**
 *
 * @author fortruth
 */
public class Adcategory extends ActionFace {

    IAdCategoryBean bean = BeanFactory.factory.getAdCatBean();

    @Override
    public void doIndex() {
        try {
            List<AdCategoryEntity> entities = bean.list();
            Field[] fields = AdCategoryEntity.class.getDeclaredFields();
            List<HashMap<String, String>> theFields = Helper.buildField(fields, module);
            
            request.setAttribute("entities", entities);
            request.setAttribute("fields", theFields);
            request.getRequestDispatcher(tableView).forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Adcategory.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Adcategory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * ajax json function
     *
     * @return
     */
    public void doSelect() {
        int theId = Integer.valueOf(request.getParameter("id"));
        AdCategoryEntity adCategoryEntity = this.bean.get(theId);
        out.print(new Gson().toJson(adCategoryEntity));
    }

    public void doUpdate() {
        AdCategoryEntity entity = new AdCategoryEntity();
        entity.setId(Integer.valueOf(request.getParameter("id")));
        this.bean.update(form2Entity(entity));
        this.doIndex();
    }

    public void doDelete() {
        int theId = Integer.valueOf(request.getParameter("id"));
        this.bean.delete(theId);
        this.doIndex();
    }

    public void doCreate() {
        AdCategoryEntity entity = new AdCategoryEntity();
        this.bean.add(form2Entity(entity));
        this.doIndex();
    }

    private AdCategoryEntity form2Entity(AdCategoryEntity entity) {
        entity.setName(Helper.toUTF8(request.getParameter("name")));
        entity.setDescription(Helper.toUTF8(request.getParameter("description")));
        entity.setUsage(Integer.valueOf(Helper.toUTF8(request.getParameter("usage"))));
        return entity;
    }
}
